<template>
  <view class="main_box">
      <view class="loginMain">
        <image class="company_icon" src="/static/image/login01.png"/>
        <view class="nh">
          您好
        </view>
        <view class="hy">
          欢迎使用
        </view>
        <view class="form">
            <input placeholder="请输入手机号" v-model="formData.userPhone" maxlength="11" />
            <input placeholder="请输入密码" type="password" v-model="formData.userPassward" />
        </view>
        <view class="loginBtn" @click="handleLogin">
          登录
        </view>
      </view>
  </view>
</template>

<script>
import { getToken, setToken, setUserInfo, getCompanyLogo } from '@/service/auth.js'
import navmixin from '@/mxins/nav.js'
import { API_login, appletCheckIsRegister } from '@/service/api/login.js'
import { encrypt } from '@/utils/func.js'
import { getLoginOpenId } from '@/service/api/wx'
import { getOpenId, getPhone, setOpenId, setSessionKey } from '@/service/auth'
import jPopup from '@/components/jPopup'

export default {
  components: { jPopup },
  mixins: [navmixin],
  data() {
    return {
      formData: {
        userPhone: '',
        userPassward: ''
      },
      showPop: false,
      mask: false,
      companyList: [],
      showCompanyName: '',
      companyCode: '',
      information: {},
      logo: '',
      typeList: [
        { id: 1, name: '地堆' },
        { id: 2, name: '冰冻' },
        { id: 3, name: '常规陈列' },
        { id: 4, name: '大排面' },
        { id: 5, name: '核心店' },
        { id: 6, name: '' }
      ]
    }
  },
  watch: {
    'formData.userPhone'(n, o) {
      if (this.formData.userPhone.length === 11) {
        this.selectCompany()
      }
    }
  },
  created() {
    this.logo = getCompanyLogo(wx.getAccountInfoSync().miniProgram.appId)
    uni.getSystemInfo({
      success: function(res) {
        console.log(res)
      }
    })
    this.formData.userPhone = uni.getStorageSync('userPhone')
    this.formData.userPassward = uni.getStorageSync('userPassward')
    // this.showPop = true
    // this.mask = true
  },
  onLoad(option) {
    if (option.token) {
      const user = JSON.parse(option.user)
      const token = option.token
      setToken(token)
      setUserInfo(user)
      const app = getApp()
      const customer = user.customerList[0]
      if (customer) app.globalData.selectedPosition = { id: customer.customerId, name: customer.customerName }
      uni.switchTab({
        url: '/pages/home/index'
      })
      return
    }
    if (option.information) {
      this.information = JSON.parse(option.information)
      this.wxlogin(this.information.companyCode)
      const username = uni.getStorageSync('userPhone')
      //判断是否有历史登录
      const historyCompany = uni.getStorageSync('companyCode')
      if (username && historyCompany === this.information.companyCode) {
        const password = uni.getStorageSync('userPassward') || '123456'
        let pData = { username: username, password: password, companyCode: this.information.companyCode }
        //尝试登录
        this.login(pData)
      } else {
        this.showPop = true
        this.mask = true
      }
    }
  },
  methods: {
    async selectCompany() {
      const { userPhone, userPassward } = this.formData
      if (userPhone.length !== 11) {
        uni.showModal({ title: '提示', content: '请输入正确手机号' })
        return false
      }
      let pData = { username: userPhone, password: encrypt(userPassward) }
      API_login(pData).then(res => {
        this.companyList = res.data.companyList
        this.companyCode = this.companyList[0].companyCode
        this.showCompanyName = this.companyList[0].companyName
        if (this.companyList.length === 1 && uni.getStorageSync('voluntarilyLogin') === 'true')
          this.voluntarilyLogin()
      }).catch(
        err => {
          this.companyList = []
          this.companyCode = ''
          this.showCompanyName = ''
        }
      )
    },
    //自动登录
    voluntarilyLogin() {
      const password = uni.getStorageSync('userPassward') || '123456'
      let pData = {
        username: this.formData.userPhone,
        password: password,
        companyCode: uni.getStorageSync('companyCode')
      }
      this.login(pData)
    },
    setCompany(item) {z
      this.showCompanyName = item.companyName
      this.companyCode = item.companyCode
    },
    //登录
    async login(pData) {
      const data = Object.assign({}, pData)
      data.password = encrypt(pData.password)
      uni.showLoading({ title: '正在登录' })
      const res = await API_login(data).catch(err => {
        if (err.status !== 200) {
          this.uniHideLoading()
          uni.showModal({ title: '提示', content: '账号或密码错误' })
        }
      })
      this.uniHideLoading()
      const {
        status,
        data: { token, user }
      } = res
      if (status == 200) {
        // 存储token 和 userInfo
        uni.setStorageSync('userPhone', pData.username)
        uni.setStorageSync('userPassward', pData.password)
        uni.setStorageSync('companyCode', pData.companyCode)
        uni.setStorageSync('voluntarilyLogin', 'true')
        setToken(token)
        setUserInfo(user)
        const app = getApp()
        const customer = user.customerList[0]
        if (customer) app.globalData.selectedPosition = { id: customer.customerId, name: customer.customerName }

        //

        console.log('登录成功')


        uni.switchTab({
          url: '/pages/home/index'
        })
      }
    },

    async getPhoneNumber(e) {
      const phone = getPhone(e.detail.encryptedData, e.detail.iv)
      this.formData.userPhone = phone.phoneNumber
      this.showPop = false
      this.mask = false
      //判断是否扫码登录
      this.information.phone = phone.phoneNumber
      uni.showLoading({ title: '正在登录' })
      const { data } = await appletCheckIsRegister({
        username: this.information.phone,
        companyCode: this.information.companyCode
      })
      //如已注册则自动登录 未注册则跳转注册页
      if (data) {
        const password = uni.getStorageSync('userPassward') || '123456'
        let pData = {
          username: this.information.phone,
          password: encrypt(password),
          companyCode: this.information.companyCode
        }
        await this.login(pData)
      } else {
        //非扫码并且单公司情况自动登录
        this.voluntarilyLogin()
      }
    },
    upCompany(e) {
      const { value } = e.target
      let company = this.companyList[value]
      this.showCompanyName = company.companyName
      this.companyCode = company.companyCode
    },

    // 账号密码 登录
    async handleLogin() {
      const { userPhone, userPassward } = this.formData
      if (!userPhone) return this.uniShowToast('请输入手机号')
      if (!userPassward) return this.uniShowToast('请输入密码')
      // if (!this.companyCode) return this.uniShowToast('请先选择公司')
      this.uniShowLoading()

      let pData = { username: userPhone, password: userPassward, companyCode: "000" }
      // let ppData = { Authorization: '', authUser: pData }
      await this.login(pData)
    },
    close() {
      this.showPop = false
      this.mask = false
    },
    wxlogin(companyCode = '000000') {

      // if (getOpenId())return
      wx.login().then(res => {
        getLoginOpenId({ code: res.code, companyCode }).then(val => {
          if (val.status === 200) {
            setOpenId(val.data.openid)
            setSessionKey(val.data.session_key)
          }
        })
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.main_box{
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding-top: 30%;
  align-items: center;
  //background-image: url("@/static/image/loginBg.png");
  background-image: url("http://129.211.211.126/download/loginBg.png") ;
  background-size: cover;
  background-repeat: repeat;
  .loginMain{
    width: 650rpx;
    .nh{
      margin-top: 30rpx;
      font-size: 60rpx;
      height: 100rpx;
      color: #333333;
    }
    .hy{
      font-size: 50rpx;
      height: 100rpx;
      color: #333333;
      font-weight: lighter;
    }
    .company_icon{
      width: 80rpx;
      height: 80rpx;
    }
    input{
      background: white;
      height: 90rpx;
      width: 100%;
      border-radius: 30rpx;
      margin-bottom: 30rpx;
      padding-left: 30rpx;
    }
    .loginBtn{
      background: #9DB6F3;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      height: 90rpx;
      border-radius: 40rpx;
    }
  }
}


</style>
